<template>
  <div class="dish-management">
    <div class="header">
      <h2>{{ departmentName }} 菜品管理</h2>
      <div class="filter-section">
        <input
            type="date"
            v-model="selectedDate"
            @change="loadDishes"
            class="date-filter"
        >
        <button class="close-btn" @click="$emit('close')">×</button>
      </div>
    </div>

    <!-- 添加菜品表单 -->
    <div class="add-dish-form">
      <input
          v-model="newDish.name"
          placeholder="菜品名称"
          required
          :class="{ 'invalid': formErrors.name }"
      >
      <input
          v-model.number="newDish.price"
          type="number"
          step="0.01"
          min="0"
          placeholder="价格"
          :class="{ 'invalid': formErrors.price }"
      >
      <input
          v-model.number="newDish.quantity"
          type="number"
          min="0"
          placeholder="数量"
          :class="{ 'invalid': formErrors.quantity }"
      >
      <button @click="addDishs" class="primary-btn">添加菜品</button>
    </div>

    <!-- 菜品列表 -->
    <table class="styled-table">
      <thead>
      <tr>
        <th>菜品名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>创建时间</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-if="dishes.length === 0">
        <td :colspan="5" class="empty-tip">
          {{ loading ? '数据加载中...' : '暂无数据' }}
        </td>
      </tr>
      <tr v-for="dish in dishes" :key="dish.id">
        <td>{{ dish.name || '未命名菜品' }}</td>
        <td>¥{{ (dish.price ?? 0).toFixed(2) }}</td>
        <td>{{ dish.quantity ?? 0 }}</td>
        <td>{{ formatDate(dish.categorizedAt) }}</td>
        <td>
          <button class="action-btn edit-btn" @click="openEdit(dish)">编辑</button>
          <button class="action-btn delete-btn" @click="deleteDishs(dish.id)">删除</button>
        </td>
      </tr>
      </tbody>

    </table>

    <!-- 编辑弹窗 -->
    <div v-if="editingDish" class="edit-modal">
      <h3>编辑菜品</h3>
      <div class="edit-form">
        <input v-model="editingDish.name" required>
        <input v-model.number="editingDish.price" type="number" step="0.01" min="0">
        <input v-model.number="editingDish.quantity" type="number" min="0">
        <div class="form-actions">
          <button @click="saveEdit" class="primary-btn">保存</button>
          <button @click="cancelEdit" class="cancel-btn">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {
  getDishesByRestaurant,
  addDish,
  updateDish,
  deleteDish
} from '@/api'

const props = defineProps({
  restaurantId: Number,
  departmentId: Number,
  departmentName: String
})

// 数据状态
const dishes = ref([])
const selectedDate = ref('')
const editingDish = ref(null)
const newDish = reactive({
  name: '',
  price: 0,
  quantity: 0,
  restaurantId: props.restaurantId,
  departmentId: props.departmentId
})

const formErrors = reactive({
  name: false,
  price: false,
  quantity: false
})

// 表单验证
const validateForm = (dish) => {
  let valid = true
  formErrors.name = !dish.name.trim()
  formErrors.price = dish.price <= 0 || isNaN(dish.price)
  formErrors.quantity = dish.quantity < 0 || isNaN(dish.quantity)

  return !(formErrors.name || formErrors.price || formErrors.quantity)
}

const loadDishes = async () => {
  try {
    const response = await getDishesByRestaurant(
        props.restaurantId,
        props.departmentId,
        selectedDate.value
    )
    console.log(response)
    dishes.value = response.data
    console.log('dishes',dishes.value)
  //   console.log('API响应结构验证:', {
  //     success: response.data.success,        // 应为 true
  //     isArray: Array.isArray(response.data.data), // 应为 true
  //     dataLength: response.data.data?.length // 应为 3
  //   })
  //
  //   // 直接使用 response.data.data
  //   dishes.value = Array.isArray(response.data.data)
  //       ? response.data.data
  //       : []
  //
  //   console.log('最终数据验证:', {
  //     dishesValue: dishes.value,
  //     isArray: Array.isArray(dishes.value),
  //     firstItem: dishes.value[0]
  //   })
  } catch (error) {
    console.error('加载失败:', error)
    dishes.value = []
    }
}
// 消息状态
const message = ref({
  show: false,
  text: '',
  type: 'info'
})

// 显示消息的方法
const showMessage = (text, type = 'info') => {
  message.value = { show: true, text, type }
  setTimeout(() => {
    message.value.show = false
  }, 3000)
}

// 添加菜品
const addDishs = async () => {
  if (!validateForm(newDish)) {
    alert('请正确填写所有字段')
    return
  }

  try {
    await addDish(newDish)
    Object.assign(newDish, {
      name: '',
      price: 0,
      quantity: 0
    })
    await loadDishes()
  } catch (error) {
    console.error('添加失败:', error)
  }
}

// 编辑功能
const openEdit = (dish) => {
  editingDish.value = { ...dish }
}

const saveEdit = async () => {
  if (!validateForm(editingDish.value)) return

  try {
    await updateDish(editingDish.value.id, editingDish.value)
    await loadDishes()
    editingDish.value = null
  } catch (error) {
    console.error('更新失败:', error)
  }
}

const cancelEdit = () => {
  editingDish.value = null
}

// 删除菜品
// 修改删除方法
const deleteDishs = async (id) => {
  if (!confirm('确定删除该菜品？')) return

  try {
    const res = await deleteDish(id)
    if (res?.success) {
      showMessage('删除成功', 'success')
      await loadDishes()
    } else {
      showMessage(res?.message || '删除失败', 'error')
    }
  } catch (error) {
    showMessage(error.response?.data?.message || '删除失败', 'error')
    console.error('删除失败:', error)
  }
  loadDishes()
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
}

onMounted(() => {
  loadDishes()
})
</script>

<style scoped>
.empty-tip {
  text-align: center;
  padding: 2rem;
  color: #666;
}
.dish-management {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 2rem;
  border-radius: 8px;
  width: 1000px;
  max-width: 95%;
  max-height: 90vh;
  overflow: auto;
  z-index: 1000;
  box-shadow: 0 0 20px rgba(0,0,0,0.2);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.filter-section {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.date-filter {
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.add-dish-form {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr auto;
  gap: 1rem;
  margin-bottom: 2rem;
}

.styled-table {
  width: 100%;
  border-collapse: collapse;

  th, td {
    padding: 1rem;
    border-bottom: 1px solid #eee;
  }

  th {
    background: #f8fafc;
  }
}

.edit-modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 0 15px rgba(0,0,0,0.1);
  z-index: 1001;

  .edit-form {
    display: grid;
    gap: 1rem;

    input {
      padding: 0.5rem;
      width: 250px;
    }
  }
}

.form-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 1rem;
}

.invalid {
  border-color: #ff4444;
  box-shadow: 0 0 0 1px #ff4444;
}
</style>